<template>
  <a-spin :spinning="confirmLoading">
    <SelectAsset
      v-if="!confirmLoading"
      :isRadioSelection="false"
      @delete="handelDeleteAsset"
      :tempPosition="{ show: true, title: '归还位置', condition: { position_type: '1' } }"
      ref="selectAsset"
      showUser
      :assetDataList="assetDataList"
      :disabled="formDisabled"
      :queryParam="{ useState: '5' }"
    />
    <div class="info-title" style="margin-top: 14px; margin-bottom: 10px">{{ common('applicationInformation') }}</div>
    <BasicForm @register="registerForm" />
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, nextTick, watchEffect } from 'vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { saveOrUpdate } from '../api';
  import { updateUseState } from '@/api/asset/assetInfo';
  import SelectAsset from '/@/views/asset/components/SelectAsset/index.vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from '../data';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t: common, isCN } = useI18n('common');
  const { t } = useI18n('asset.assetReturn');
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    fData: { type: Object, default: () => {} },
    formBpm: { type: Boolean, default: true },
    assetDataList: { type: Array, required: true },
  });
  const emit = defineEmits(['register', 'ok', 'deleted']);
  const formData = reactive<Record<string, any>>({});
  const { createMessage } = useMessage();
  const confirmLoading = ref<boolean>(false);
  //表单配置
  const [registerForm, { setProps, resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: isCN ? 100 : 180,
    schemas: formSchema,
    showActionButtonGroup: false,
    baseColProps: { span: 12 },
  });
  watchEffect(() => {
    if (props.formBpm === true) {
      if (props.fData.disabled === false) {
        return setProps({ disabled: false });
      } else {
        return setProps({ disabled: true });
      }
    }
    return setProps({ disabled: props.formDisabled });
  });
  /**
   * 新增
   */
  function add() {
    if (import.meta.env.DEV) {
      edit({
        userId: 'huangrui',
        collectionPositionId: '1729767372975652866',
        departmentId: '1582683631414632450',
        description: '这是一段描述声明' + Date.now(),
        returnTime: '2024-01-12',
        status: '1',
      });
    } else {
      edit({
        status: '1',
      });
    }
  }

  /**
   * 编辑
   */
  function edit(record) {
    nextTick(async () => {
      resetFields();
      //赋值
      Object.assign(formData, record);
      await setFieldsValue({
        ...record,
      });
    });
  }
  function handelDeleteAsset(record) {
    updateUseState({ billid: formData.id, assertId: record.id });
    if (typeof formData.assetList === 'string') {
      formData.assetList = formData.assetList.split(',');
    }
    const index = formData.assetList?.indexOf(record.id);
    formData.assetList.splice(index, 1);
    formData.positionList.split(',').splice(index, 1);
    saveOrUpdate({ id: formData.id, assetList: formData.assetList.toString(), positionList: formData.positionList.toString() }, true).then((res) => {
      console.log(res, 'handelDeleteAsset');
      if (res.success) {
        emit('deleted', formData.assetList);
      } else {
        createMessage.error('删除失败');
      }
    });
  }
  /**
   * 提交数据
   */
  const selectAsset = ref<InstanceType<typeof SelectAsset>>();
  async function submitForm() {
    // 触发表单验证
    const values = await validate();
    Object.assign(formData, values);
    const selectedData = selectAsset.value?.getSelectedData();
    formData.assetList = selectedData?.id;
    if (!formData.assetList?.length) {
      createMessage.error(common('chooseText') + t('assetTitle'));
      return;
    }
    const positionList: string[] = [];
    selectedData?.data.forEach(({ tempPosition, name }) => {
      if (tempPosition) {
        positionList.push(tempPosition);
      } else {
        createMessage.error(name + '未选择归还位置');
      }
    });
    console.log(positionList, selectedData?.data, 'selectedData');
    if (formData.assetList?.length !== positionList.length) {
      return;
    }
    confirmLoading.value = true;

    //时间格式化
    let model = formData;
    model.positionList = positionList.toString();
    model.assetList = model.assetList.toString();
    const isupdate = !!model.id;
    await saveOrUpdate(model, isupdate)
      .then((res) => {
        if (res.success) {
          const tip = {
            '1': '保存成功',
            '2': '提交成功',
          };
          createMessage.success(tip[res.result.status]);
          emit('ok', res.result);
          emit('deleted', formData.assetList.toString());
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }

  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    min-height: 500px !important;
    overflow-y: auto;
    padding: 24px 24px 24px 24px;
  }
  .info-title {
    font-size: 15px;
    font-weight: 600;
  }
</style>
